<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // 检查字段是否已存在，避免重复添加
            if (!Schema::hasColumn('users', 'website')) {
                $table->string('website')->nullable()->after('bio');
            }
            if (!Schema::hasColumn('users', 'github')) {
                $table->string('github')->nullable()->after('website');
            }
            if (!Schema::hasColumn('users', 'twitter')) {
                $table->string('twitter')->nullable()->after('github');
            }
            if (!Schema::hasColumn('users', 'linkedin')) {
                $table->string('linkedin')->nullable()->after('twitter');
            }
            if (!Schema::hasColumn('users', 'location')) {
                $table->string('location')->nullable()->after('linkedin');
            }
            if (!Schema::hasColumn('users', 'occupation')) {
                $table->string('occupation')->nullable()->after('location');
            }
            if (!Schema::hasColumn('users', 'followers_count')) {
                $table->unsignedInteger('followers_count')->default(0)->after('occupation');
            }
            if (!Schema::hasColumn('users', 'following_count')) {
                $table->unsignedInteger('following_count')->default(0)->after('followers_count');
            }
            if (!Schema::hasColumn('users', 'posts_count')) {
                $table->unsignedInteger('posts_count')->default(0)->after('following_count');
            }
            if (!Schema::hasColumn('users', 'allow_email_notifications')) {
                $table->boolean('allow_email_notifications')->default(true)->after('posts_count');
            }

            // 添加索引
            $table->index(['followers_count']);
            $table->index(['following_count']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // 删除索引
            $table->dropIndex(['followers_count']);
            $table->dropIndex(['following_count']);

            // 删除字段
            $columns = [
                'website', 'github', 'twitter', 'linkedin',
                'location', 'occupation', 'followers_count',
                'following_count', 'posts_count', 'allow_email_notifications'
            ];

            foreach ($columns as $column) {
                if (Schema::hasColumn('users', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};